class Solution {
    int left,right,n;
    StringBuffer path;
    List<String> ret;
    public List<String> generateParenthesis(int _n) {
        n = _n;
        path = new StringBuffer();
        ret = new ArrayList<>();

        dfs();

        return ret;
    }

    public void dfs() {
        //递归出口
        if(right==n) {
            ret.add(path.toString());
            return;
        }

        if(left<n) {//添加左括号
            path.append('(');
            left++;
            dfs();
            path.deleteCharAt(path.length()-1);//恢复现场
            left--;
        }

        if(right<left) {
            path.append(')');
            right++;
            dfs();
            path.deleteCharAt(path.length()-1);//恢复现场
            right--;
        }
    }
}
